<!--
 * @FilePath: /web-vue/src/views/SysUserDept/index.vue
 * @Description: 【用户部门关联表】管理主页
-->
<template>
  <div>
    <el-row class="data-table row-panel row-panel-first">
      <el-col>
        <el-card>
          <el-row :gutter="0">
            <!-- 【用户部门关联表】参数 -->
            <el-col>
              <el-form :model="queryForm" size="medium" :inline="true">
                <table style="border-collapse: collapse; width: 100%" class="table-common-style">
                  <colgroup>
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                  </colgroup>
                  <tbody>
                    <tr>
                      <td><div class="form-item-label">ID：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="id">
                          <el-input v-model.trim="queryForm.id" placeholder="请输入查询参数" clearable>
                          </el-input>
                        </el-form-item>
                      </td>
                      <td><div class="form-item-label">用户ID：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="userId">
                          <el-input v-model.trim="queryForm.userId" placeholder="请输入查询参数" clearable>
                          </el-input>
                        </el-form-item>
                      </td>
                      <td><div class="form-item-label">部门ID：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="deptId">
                          <el-input v-model.trim="queryForm.deptId" placeholder="请输入查询参数" clearable>
                          </el-input>
                        </el-form-item>
                      </td>
                    </tr>
                    <tr>
                      <td colspan="10">
                        <!-- 按钮 -->
                        <el-form-item>
                          <el-button
                            type="primary"
                            icon="el-icon-search"
                            @click="queryDataBtn()"
                            :loading="requestLoading"
                            >查询
                          </el-button>
                          <el-button
                            type="success"
                            icon="el-icon-s-custom"
                            @click="$refs.addForm.openAddForm(true)"
                            >新增
                          </el-button>
                          <el-button
                            type="danger"
                            icon="el-icon-delete"
                            @click="batchDelSysUserDeptApi()"
                            >删除
                          </el-button>
                        </el-form-item>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </el-form>
            </el-col>
            <!-- 【用户部门关联表】信息表 -->
            <el-col>
              <el-divider content-position="left">
                <h3>用户部门关联表信息表</h3>
              </el-divider>
              <el-table
                :data="tableData"
                border
                highlight-current-row
                max-height="400"
                @selection-change="handleTableRowsSelect"
                v-loading="requestLoading"
                element-loading-text="正在拼命加载，请耐心等待！"
                element-loading-spinner="el-icon-loading"
              >
                <el-table-column type="selection" width="55" align="center">
                </el-table-column>
                <el-table-column fixed="left" label="操作" width="100%" align="center">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-edit-outline"
                      @click="$refs.editForm.openEditForm(true, scope.row)"
                      >变更
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column type="index" label="序号" width="80" align="center"
                ></el-table-column>
                <el-table-column prop="id" label="ID" align="center"
                ></el-table-column>
                <el-table-column prop="userId" label="用户ID" align="center"
                ></el-table-column>
                <el-table-column prop="deptId" label="部门ID" align="center"
                ></el-table-column>
              </el-table>
            </el-col>
            <!-- 分页组件 -->
            <el-col>
              <el-pagination
                background
                @size-change="handlePageSizeChange"
                @current-change="handleCurrentPageChange"
                :current-page="page.currentPage"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="page.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.total"
                align="center"
              >
              </el-pagination>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加xxx表单 -->
    <AddForm ref="addForm" @afterSubmit="afterSubmitHandle()"></AddForm>
    <!-- 编辑xxx表单 -->
    <EditForm ref="editForm" @afterSubmit="afterSubmitHandle()"></EditForm>
  </div>
</template>

<script>
import AddForm from "./addForm";
import EditForm from "./editForm";

const datePickerOptions = {
  shortcuts: [
    {
      text: "最近一周",
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        picker.$emit("pick", [start, end]);
      },
    },
    {
      text: "最近一个月",
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        picker.$emit("pick", [start, end]);
      },
    },
    {
      text: "最近三个月",
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        picker.$emit("pick", [start, end]);
      },
    },
  ],
}

export default {
  name: "sysUserDeptManage",
  components: {
    AddForm,
    EditForm,
  },

  data() {
    return {
      // 分页参数
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      // 【用户部门关联表】数据表
      tableData: [],
      // 【用户部门关联表】表已选 IDs
      tableCheckIds: [],
      // 数据加载
      requestLoading: false,
      // 查询表单参数
      queryForm: {
        id: null,
        userId: null,
        deptId: null,
      },
      // 日期选择快捷方式
      pickerOptions: datePickerOptions
    };
  },

  // 组件创建时
  created() {
    // 页面元素初始化
  },

  // 组件挂载时
  mounted() {
    // 初始化字典
  },

  methods: {
    // 表单提交后置处理
    afterSubmitHandle() {
      this.querySysUserDeptApi();
      this.tableCheckIds = [];
    },

    // 处理表格行多选
    handleTableRowsSelect(val) {
      let ids = [];
      val.forEach(obj => ids.push(obj.id));
      this.tableCheckIds = ids;
    },

    // ---------------- 分页参数处理 START-----------------
    handleCurrentPageChange(val) {
      this.page.currentPage = val;
      // 查询【用户部门关联表】表
      this.querySysUserDeptApi();
    },
    handlePageSizeChange(val) {
      this.page.pageSize = val;
      this.page.currentPage = 1;
      // 查询【用户部门关联表】表
      this.querySysUserDeptApi();
    },
    // ---------------- 分页参数处理 END-----------------

    // 查询【用户部门关联表】
    queryDataBtn() {
      this.page.currentPage = 1;
      this.querySysUserDeptApi();
    },

    // 删除数据后：最后一页逻辑处理、表格更新
    afterDelete(deleteCount) {
      // 最后一页（旧）
      let oldLastPage = Math.ceil(this.page.total / this.page.pageSize);
      // 最后一页（新）
      let currLastPage = Math.ceil(
              (this.page.total - deleteCount) / this.page.pageSize
      );
      // 如果删除最后一页，则将当前页更新为最新的最后一页
      if (this.page.currentPage == oldLastPage) {
        this.page.currentPage = currLastPage == 0 ? 1 : currLastPage;
      }
      // 更新表格
      this.querySysUserDeptApi();
    },

    // 查询参数处理
    queryParamProcess() {
      let param = Object.assign({}, this.queryForm);
      param["pageNum"] = this.page.currentPage;
      param["pageSize"] = this.page.pageSize;



      return param;
    },

    // 查询【用户部门关联表】API
    querySysUserDeptApi() {
      this.requestLoading = true;
      let vueIns = this; // 局部变量指向当前 Vue 实例，解决 catch 块中的this引用为 undefined
      this.$api
        .querySysUserDept(this.queryParamProcess())
        .then((res) => {
          this.tableData = [];
          this.page.total = 0;

          let { status, message, data } = res.data;
          if (status == 200) {
            this.tableData = data.items;
            this.page.total = data.totalNum;
          } else if (status == 403) {
            this.$message({
              message: `权限不足！${message}`,
              type: "error",
              center: true,
              duration: 1680,
            });
          } else {
            this.$alert(`暂无数据记录！${message}`, "【用户部门关联表】信息表", {
              type: "info",
              confirmButtonText: "确定",
              callback: (action) => {},
            });
          }

          this.requestLoading = false;
        })
        .catch(function(err) {
          vueIns.requestLoading = false;
          console.log(`【用户部门关联表】查询接口发生错误: ${err}`);
        });
    },

    // 删除【用户部门关联表】API
    batchDelSysUserDeptApi() {
      if (this.tableCheckIds.length == 0) {
        this.$alert("请在左侧列选中要删除的行！", "提示", {
          confirmButtonText: "确定",
          type: "warning",
          callback: (action) => {},
        });
        return;
      }

      this.$confirm("此操作将永久删除已选中的数据, 是否继续?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      })
      .then(() => {
        const loading = this.$loading({
          target: document.querySelector(".data-table"),
          lock: true,
          text: "正在删除，请耐心等待！",
        });

        let vueIns = this; // 局部变量指向当前 Vue 实例，解决 catch 块中的this引用为 undefined
        // 发起删除请求
        this.$api
          .batchDelSysUserDept({ ids: this.tableCheckIds })
          .then((res) => {
            loading.close();

            let { status, message, data } = res.data; // 响应数据
            if (status == 200) {
              // 更新【用户部门关联表】表
              this.afterDelete(data);
              // 提示信息
              this.$message({
                type: "success",
                message: `删除成功！删除记录数：${data}`,
                duration: 1680,
              });
            } else if (status == 403) {
              this.$message({
                message: `权限不足！${message}`,
                type: "error",
                center: true,
                duration: 1680,
              });
              // this.$router.push("/login");
            } else {
              this.$message({
                type: "warning",
                message: `数据没有发生更改！${message}`,
                duration: 1680,
              });
            }
          })
          .catch(function(err) {
          loading.close();
          // 查询【用户部门关联表】表
          vueIns.querySysUserDeptApi();
          console.log(`【用户部门关联表】删除接口发生错误: ${err}`);
        });
      })
      .catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除。",
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
// 表单布局样式
@import "@/assets/css/form-layout.scss";
</style>
